<template>
  <div>
    <h3>库存管理表格</h3>
    <el-input
        placeholder="请输入物资名称"
        v-model="searchQuery"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="fetchInventory"
    />
    <el-button type="primary" @click="searchInventory">搜索</el-button>
    <el-button type="primary" @click="openDialog">添加库存</el-button>
    <el-table :data="inventory" style="width: 100%; margin-top: 20px;">
      <!-- 表格列定义 -->
      <el-table-column prop="name" label="物资名称" width="180"></el-table-column>
      <el-table-column prop="supplier" label="供应商" width="180"></el-table-column>
      <el-table-column prop="type" label="物资类型" width="180"></el-table-column>
      <el-table-column prop="number" label="数量" width="180"></el-table-column>
      <el-table-column prop="purchaseDate" label="采购日期" width="180"></el-table-column>
      <el-table-column prop="storageDate" label="入库日期" width="180"></el-table-column>
      <el-table-column prop="storagePerson" label="入库人" width="180"></el-table-column>
      <el-table-column prop="deliveryDate" label="出库日期" width="180"></el-table-column>
      <el-table-column prop="deliveryPerson" label="出库人" width="180"></el-table-column>
      <el-table-column prop="storageArea" label="存储区域" width="180"></el-table-column>
      <el-table-column prop="fillDate" label="填写日期" width="180"></el-table-column>
      <el-table-column prop="operator" label="操作员" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" @click="editInventory(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteInventory(scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="isEdit ? '编辑库存' : '添加库存'" v-model="dialogVisible">
      <el-form :model="newInventory" :rules="rules" ref="inventoryForm">
        <!-- 表单项定义 -->
        <el-form-item label="物资名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="newInventory.name"></el-input>
        </el-form-item>
        <el-form-item label="供应商" :label-width="formLabelWidth" prop="supplier">
          <el-input v-model="newInventory.supplier"></el-input>
        </el-form-item>
        <el-form-item label="物资类型" :label-width="formLabelWidth" prop="type">
          <el-input v-model="newInventory.type"></el-input>
        </el-form-item>
        <el-form-item label="数量" :label-width="formLabelWidth" prop="number">
          <el-input v-model="newInventory.number" type="number"></el-input>
        </el-form-item>
        <el-form-item label="采购日期" :label-width="formLabelWidth" prop="purchaseDate">
          <el-date-picker v-model="newInventory.purchaseDate" type="date" placeholder="选择采购日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="入库日期" :label-width="formLabelWidth" prop="storageDate">
          <el-date-picker v-model="newInventory.storageDate" type="date" placeholder="选择入库日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="入库人" :label-width="formLabelWidth" prop="storagePerson">
          <el-select v-model="newInventory.storagePerson" placeholder="请选择入库人">
            <el-option v-for="person in persons" :key="person.id" :label="person.name" :value="person.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出库日期" :label-width="formLabelWidth" prop="deliveryDate">
          <el-date-picker v-model="newInventory.deliveryDate" type="date" placeholder="选择出库日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="出库人" :label-width="formLabelWidth" prop="deliveryPerson">
          <el-select v-model="newInventory.deliveryPerson" placeholder="请选择出库人">
            <el-option v-for="person in persons" :key="person.id" :label="person.name" :value="person.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存储区域" :label-width="formLabelWidth" prop="storageArea">
          <el-select v-model="newInventory.storageArea" placeholder="请选择存储区域">
            <el-option v-for="area in areas" :key="area.id" :label="area.name" :value="area.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="填写日期" :label-width="formLabelWidth" prop="fillDate">
          <el-date-picker v-model="newInventory.fillDate" type="date" placeholder="选择填写日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="操作员" :label-width="formLabelWidth" prop="operator">
          <el-input v-model="newInventory.operator"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateInventory">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      inventory: [],
      persons: [],
      areas: [],
      dialogVisible: false,
      isEdit: false,
      searchQuery: '',
      newInventory: {
        name: '',
        supplier: '',
        type: '',
        number: '',
        purchaseDate: '',
        storageDate: '',
        storagePerson: '',
        deliveryDate: '',
        deliveryPerson: '',
        storageArea: '',
        fillDate: '',
        operator: ''
      },
      formLabelWidth: '120px',
      rules: {
        name: [{ required: true, message: '请输入物资名称', trigger: 'blur' }],
        supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
        type: [{ required: true, message: '请输入物资类型', trigger: 'blur' }],
        number: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        purchaseDate: [{ required: true, message: '请选择采购日期', trigger: 'blur' }],
        storageDate: [{ required: true, message: '请选择入库日期', trigger: 'blur' }],
        storagePerson: [{ required: true, message: '请选择入库人', trigger: 'change' }],
        deliveryDate: [{ required: true, message: '请选择出库日期', trigger: 'blur' }],
        deliveryPerson: [{ required: true, message: '请选择出库人', trigger: 'change' }],
        storageArea: [{ required: true, message: '请选择存储区域', trigger: 'change' }],
        fillDate: [{ required: true, message: '请选择填写日期', trigger: 'blur' }],
        operator: [{ required: true, message: '请输入操作员', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.fetchInventory();
    this.fetchPersons();
    this.fetchAreas();
  },
  methods: {
    fetchInventory() {
      axios.get('http://localhost:8081/api/goods/getall')
          .then(response => {
            this.inventory = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the inventory!", error);
          });
    },
    fetchPersons() {
      axios.get('http://localhost:8081/api/goods/persons')
          .then(response => {
            this.persons = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the persons!", error);
          });
    },
    fetchAreas() {
      axios.get('http://localhost:8081/api/goods/areas')
          .then(response => {
            this.areas = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the areas!", error);
          });
    },
    searchInventory() {
      axios.get(`http://localhost:8081/api/goods/get/${this.searchQuery}`)
          .then(response => {
            this.inventory = [response.data];
          })
          .catch(error => {
            console.error("There was an error searching the inventory!", error);
          });
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetInventory();
    },
    editInventory(inventory) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.newInventory = {...inventory};
    },
    addOrUpdateInventory() {
      this.$refs.inventoryForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            axios.put('http://localhost:8081/api/goods/update', this.newInventory)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchInventory();
                  this.resetInventory();
                  ElMessage.success('库存更新成功');
                })
                .catch(error => {
                  console.error("There was an error updating the inventory!", error);
                  ElMessage.error('库存更新失败');
                });
          } else {
            axios.post('http://localhost:8081/api/goods/add', this.newInventory)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchInventory();
                  this.resetInventory();
                  ElMessage.success('库存添加成功');
                })
                .catch(error => {
                  console.error("There was an error adding the inventory!", error);
                  ElMessage.error('库存添加失败');
                });
          }
        }
      });
    },
    deleteInventory(name) {
      axios.delete(`http://localhost:8081/api/goods/delete/${name}`)
          .then(() => {
            this.fetchInventory();
            ElMessage.success('库存删除成功');
          })
          .catch(error => {
            console.error("There was an error deleting the inventory!", error);
            ElMessage.error('库存删除失败');
          });
    },
    resetInventory() {
      const username = localStorage.getItem('username');
      this.newInventory = {
        name: '',
        supplier: '',
        type: '',
        number: '',
        purchaseDate: '',
        storageDate: '',
        storagePerson: '',
        deliveryDate: '',
        deliveryPerson: '',
        storageArea: '',
        fillDate: '',
        operator: username || ''
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
